//package MASSHEATWAVE;


//package mass.heatwave;

import MASS.*;
import java.io.IOException;
import java.util.List;
import ucar.ma2.ArrayFloat;
import ucar.ma2.IndexIterator;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;

/**
 *
 * @author brett
 */
public class MASSHEATWAVE {

    // CONSTANTS - MASS arguments
    static final String[] MASSARGS = { "dslab","dslab", "machinefile.txt","12345" };
    static final int NPROCESSES = 1;
    static final int NTHREADS = 1;

    // CONSTANTS - functions
    public static final int computeTemp_ = 1;

    
    // CONSTANTS - heatwave constants
    public static final int DAYS = 30;
    public static final int DAYSEGMENTS = 4;
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        System.err.println("INITIALIZING MASS"); 
	MASS.init( MASSARGS, NPROCESSES, NTHREADS ); 
        
        // Places
        Places computeHeatWave = new Places( 1, "MASSHEATWAVE", null, DAYSEGMENTS, DAYS );
        
        Object[] results = computeHeatWave.callAll(computeTemp_, null);
        
        int counter = 0;
        for (int i = 0; i < results.length; ++i) {
            System.err.println(++counter + ": " + results[i]);
        }
//        // validate the arguments.
//	if ( args.length < 8 ) {
//	  System.err.println( "usage: " +
//						 "login pass port size time graph_interval " +
//						 "#processes #threads showGfx" );
//	  System.exit( -1 );
//	}
//        String login = args[0];
//        String password = args[1];
//        String port = args[2];
//	int size = Integer.parseInt( args[3] );
//	int maxTime = Integer.parseInt( args[4] );
//	int interval = Integer.parseInt( args[5] );
//	int nProcesses = Integer.parseInt( args[6] );
//	int nThreads = Integer.parseInt( args[7] );
////        boolean showGraphics = args.length == 9 ? true : false;
//
//	System.out.println("Grid: " + args[3] + "\tDuration: " + args[4]);
//
//
//	// start MASS
////	MASS.init( args, nProcesses, nThreads ); //commented out in original
//	String[] massArgs = new String[4];
//	massArgs[0] = login;            // user name
//	massArgs[1] = password;          // password
//        massArgs[2] = "machinefile.txt";    // machine file
//        massArgs[3] = port;
//        System.err.println("INITIALIZING MASS"); 
//	MASS.init( massArgs, nProcesses, nThreads ); 
//	
//	// create a Wave2D array
//	Places computeTimeHelloWorld = new Places( 1, "MASS_Hello_World", ( Object )( new Integer( interval ) ), size, size );
//        System.err.println("CALLING ALL INIT"); 
//	computeTimeHelloWorld.callAll( init_, null );
//        
//	
//	// start graphics
////	if ( interval > 0 && showGraphics )
//        System.err.println("STARTING GRAPHICS");
//	  computeTimeHelloWorld.callSome( startGraphics_, (Object)null, 0, 0 );
////        computeTimeHelloWorld.callAll( startGraphics_, null);
//	
//	// define the four neighbors of each cell
////	Vector<int[]> neighbors = new Vector<int[]>( );
////	int[] north = {  0, -1 }; neighbors.add( north );
////	int[] east  = {  1,  0 }; neighbors.add( east );
////	int[] south = {  0,  1 }; neighbors.add( south );
////	int[] west  = { -1,  0 }; neighbors.add( west );
//	
////	Date startTime = new Date( );
//	
////	long ca_time_total = 0;
////	long ea_time_total = 0;
//
//	// now go into a cyclic simulation
//	for ( int time = 0; time < maxTime; time++ ) {
////	    Date ca_start = new Date();
//            System.err.println("CALL ALL ITERATION: " + time);
//	  computeTimeHelloWorld.callAll( computeTime_, ( Object )( new Integer( time ) ) );
////	  Date ca_stop = new Date();
////	  ca_time_total += (ca_stop.getTime() - ca_start.getTime());
////	  Date ea_start = new Date();
////	  wave2D.exchangeAll( 1, exchangeWave_, neighbors );
////	  Date ea_stop = new Date();
////	  ea_time_total += (ea_stop.getTime() - ea_start.getTime()); 
//	  // at every given time interval, display the array contents
//	  
//	   // some testing lines to make a certain square red
//		  //if (!testWithNoGraphics){
//		 // wave2D.callSome( doSpecial_, (Object)null, 5, 5); 
//		//  }
//		 // }
//	
//            if ( time % interval == 0 ) {
//    //		Object[] waves = wave2D.callAll( collectWave_, (Object[])null );
//                System.err.println("AFTER COLLECT TIME ITERATION: " + time);
//                Object[] times = computeTimeHelloWorld.callAll(collectTime_, null);
//    //		if (showGraphics) 
//                 System.err.println("WRITE GRAPHICS ITERATION: " + time);   
//                    computeTimeHelloWorld.callSome( writeToGraphics_, (Object)times, 0, 0 );
//                    
////                    computeTimeHelloWorld.callAll( writeToGraphics_, null);
//            } 
//	}
//	
////	Date endTime = new Date( );
////	System.out.println( "\tTime (ms): " +
////					   ( endTime.getTime( ) - startTime.getTime( ) ) );
////	System.out.println("exchangeAll time: " + ea_time_total + "\tcallAll time: " + ca_time_total);
//	
//	// stop graphics
////	if ( interval > 0 && showGraphics)
////	   
//        System.err.println("BEFORE FINISH GRAPHICS CALL ALL"); 
//        //computeTimeHelloWorld.callAll( finishGraphics_, null );
//        computeTimeHelloWorld.callSome( finishGraphics_, (Object) null, 0, 0 ); 
//        System.err.println("AFTER FINISH GRAPHICS CALL ALL"); 
//	
//	MASS.finish( );
    }

public Object callMethod( int funcId, Object args ) {
	switch( funcId ) {
	  case computeTemp_: return computeTemp( args );

	}
	return null;
  }

 public Object computeTemp( Object args ) {
NetcdfFile stubby = null;

        try {
            stubby = NetcdfFile.open("/home/brett/7&8 CSS595_596 - Capstone Project I & II/NetBeans Projects/MASS Heatwave/src/mass/heatwave/wrfout_d02_1980-01-01_120000.nc", null);	// Open the file
            List<Variable> stubbyVars = stubby.getVariables();	// Get list of file's variables

            System.out.println("Number of variables in file: " + stubbyVars.size());
            System.out.println();
            
            System.out.println("getdetailinfo: " + stubby.getDetailInfo());
            System.out.println("filetypedesc " + stubby.getFileTypeDescription());

            // ~~~~~~~~~~~~~ Read each variables ~~~~~~~~~~~~~ //
            Variable curr = stubbyVars.get(stubbyVars.indexOf("T2"));
            
//            for (int i = 0; i < stubbyVars.size(); i++) {
//                
//                    //Variable curr = stubbyVars.get(i);		// Get the current Variable
//                    //System.out.println(curr.getFullName());
//                    
//                    if( curr.getFullName().equals("T2")) {
                    
                        //System.out.print("Index " + i + ": ");

                        ArrayFloat.D3 d3values = (ArrayFloat.D3)curr.read();
                        //System.out.println("XXXXXXXX " + d3values.getSize() + "XXXXXXXXXXXXXXXX");
                        
                       
                        //RangeIterator rngs = d3values.getRangeIterator(rngs);
                        //Index indx = d3values.getIndex();
                        
                        //System.out.println(indx.getShape(0) + ", " + indx.getShape(1) + ", " + indx.getShape(2));
                        
                        double totalTemp = 0.0;                        
                                                
                        IndexIterator iter = d3values.getIndexIterator();
                        while (iter.hasNext()) {
                            iter.next();
//                            System.out.print(iter.getCurrentCounter()[0] + 
//                                    ", " + iter.getCurrentCounter()[1] + ", " + 
//                                    iter.getCurrentCounter()[2] + ": " + iter.getFloatCurrent() + " ");
                            totalTemp += (double)iter.getFloatCurrent();
                        }
                        double avgTemp = totalTemp / d3values.getSize();
                        
                        //System.out.println("Average Temperature at this time: " + avgTemp);
                        
                        //}

                        return (Object)avgTemp;
                // ~~~~~~~~~~~~~ Done ~~~~~~~~~~~~~ //		

            } catch (java.io.IOException e) {
                e.printStackTrace();
            } finally {		// Close out the file no matter what occurs
                if (stubby != null)
                    try {
                        System.err.println("In finally");
                            stubby.close();
                    } catch (IOException ioe) {
                            ioe.printStackTrace();
                    }
            }
      return null;
  }


}